<template>
	<div v-loading="load.load">
		<userDistribution :total_channel="total_channel" unit="笔" />
		<div class="adminMain">
			<el-row class="tableBtnTop">
				<el-select v-model="field.id" placeholder="请选择" class="filter">
					<el-option v-for="(item, index) in field.list" :label="item.label" :key="item.key" :value="item.value"></el-option>
				</el-select>
				<div class="search">
					<el-input placeholder="请搜索" v-model="keyword" @keyup.enter.native="page = 1;getList()">
						<i slot="prefix" class="el-input__icon el-icon-search"></i>
					</el-input>
				</div>
				<el-date-picker type="daterange" v-model="time" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd" style="width:400px;margin-right:15px;" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" popper-class="index_promotionData_daterange_popper_class"></el-date-picker>
				<el-button class="f1" @click="getList">立即搜索</el-button>
				<div class="tableRight">
					<a class="color" @click="findStatusIOS">查询iOS订阅状态</a>
				</div>
			</el-row>
			<el-table :data="tableData" border @filter-change="filterChange">
				<el-table-column prop="" label="第三方订单号" :show-overflow-tooltip="false">
					<template slot-scope="scope">
						<el-popover
						    placement="top-start"
						    title="订单号"
						    width="300"
						    trigger="hover">
							<div class="userLog">
								<div class="item flex">
									<div class="left ell">第三方订单号</div>
									<div class="right ell">{{ scope.row.transaction_id || "-" }}</div>
								</div>
								<div class="item flex">
									<div class="left ell">商户单号</div>
									<div class="right ell">{{ scope.row.pay_tenant_no || "-" }}</div>
								</div>
							</div>
						    <span slot="reference">{{ scope.row.transaction_id || "-" }}</span>
						</el-popover>
					</template>
				</el-table-column>
				<el-table-column prop="" label="用户" :show-overflow-tooltip="true">
					<template slot-scope="scope">
						<div class="device_view flex" v-if="scope.row.user_info">
							<a class="userHead" target="_blank" :href="`/user/detail?id=${scope.row.user_info.id}`">
								<img :src="scope.row.user_info.avatar" v-if="scope.row.user_info.avatar" class="square" />
								{{ scope.row.user_info.nickname || "-" }}
							</a>
						</div>
						<template v-else></template>
					</template>
				</el-table-column>
				<el-table-column prop="" label="购买套餐" :show-overflow-tooltip="true" :filters="filerComputed('plan_id').select" :filtered-value="filerComputed('plan_id').value" column-key="plan_id">
					<template slot-scope="scope">
						<template v-if="scope.row.plan_info">{{ scope.row.plan_info.vip_name }} - {{ scope.row.plan_info.title }}</template>
						<template v-else>-</template>
					</template>
				</el-table-column>
				<el-table-column prop="" label="支付方式" :show-overflow-tooltip="true" :filters="filerComputed('pay_type').select" :filtered-value="filerComputed('pay_type').value" column-key="pay_type">
					<template slot-scope="scope">
						<template v-if="scope.row.pay_type === 'w'">微信</template>
						<template v-if="scope.row.pay_type === 'a'">支付宝</template>
						<template v-if="scope.row.pay_type === 'apple'">苹果支付</template>
						<template v-if="scope.row.pay_type === 'system'">系统赠送</template>
					</template>
				</el-table-column>
				<el-table-column prop="" label="支付时渠道" :show-overflow-tooltip="true" :filters="filerComputed('pay_channel').select" :filtered-value="filerComputed('pay_channel').value" column-key="pay_channel">
					<template slot-scope="scope">{{ scope.row.pay_channel || "-" }}</template>
				</el-table-column>
				<el-table-column prop="" label="类型" :show-overflow-tooltip="true" :filters="filerComputed('order_action').select" :filtered-value="filerComputed('order_action').value" column-key="order_action">
					<template slot-scope="scope">{{ scope.row.order_action === 1 ? '今日新购' : scope.row.order_action === 2 ? '非今日新购' : '复购' }}</template>
				</el-table-column>
				<el-table-column prop="" label="支付状态" :show-overflow-tooltip="true">
					<template slot-scope="scope">
						<template v-if="scope.row.iapLoad">
							<div class="flex smallLoad">
								<span>加载中..</span>
								<span class="el-icon-loading"></span>
							</div>
						</template>
						<template v-else>
							<template v-if="scope.row.iapResult">
								<template v-if="scope.row.iapResult.pending_renewal_info && scope.row.iapResult.pending_renewal_info.length > 0">
									<template v-for="(item) in scope.row.iapResult.pending_renewal_info">
										<font color="#F30" v-if="item.auto_renew_status === '0'">已取消，</font>
										<template v-if="item.auto_renew_status === '1'">续订中，</template>
									</template>
								</template>
								<template v-else>没有订阅，</template>
								<el-popover v-if="countRefund(scope.row.iapResult).length > 0" placement="top-start" title="退款记录" width="400" trigger="hover">
									<div class="userLog">
										<div class="item flex" v-for="(item, index) in countRefund(scope.row.iapResult)">
											<div class="left ell">时间{{ item.cancellation_date }}，</div>
											<div class="right ell">原因：{{ item.cancellation_reason }}</div>
										</div>
									</div>
									<font slot="reference" color="#F30">{{ countRefund(scope.row.iapResult).length }}笔退款</font>
								</el-popover>
								<template v-else>未退款</template>
							</template>
							<template v-else>
								{{ scope.row.pay_status === 0 ? "待支付" : scope.row.pay_status === 1 ? "已支付" : "已退款" }}
								<el-button size="mini" style="transform: scale(0.85);margin-left:5px; padding: 6px 8px;font-size:13px;" @click="refund(scope.$index)" v-if="(scope.row.pay_type === 'w' || scope.row.pay_type === 'a') && scope.row.pay_status === 1">退款</el-button>
							</template>
						</template>
					</template>
				</el-table-column>
				<adsTableColumn :ascribeList="filerComputed('ascribe_type').select" :ascribeIds="filerComputed('ascribe_type').value"></adsTableColumn>
				<el-table-column prop="" label="订单金额" :show-overflow-tooltip="true">
					<template slot-scope="scope">
						<span :style="{ textDecoration: scope.row.pay_status === 2 ? 'line-through' : '', color: '#F30' }">{{ scope.row.pay_amount || "-" }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="" label="支付时间">
					<template slot-scope="scope">{{ scope.row.created_at || "-" }}</template>
				</el-table-column>
			</el-table>
			<div class="paginationBlock">
				<el-pagination layout="prev, pager, next, sizes, total" @size-change="getList" @current-change="getList" :total="total" :current-page.sync="page" :page-size.sync="limit" ></el-pagination>
			</div>
		</div>
	</div>
</template>

<script>
	import adsTableColumn from '@/components/adsTableColumn.vue';
	import userDistribution from '@/components/userDistribution.vue';
	export default {
		components: { adsTableColumn, userDistribution },
		data() {
			return {
				
				// 是否处于加载中
				load: { load: false },
				
				// 统计数据
				total_channel: null,
				
				// 表格数据
				tableData: [],
				
				// 当前页数
				page: this.$route.query.page ? parseInt(this.$route.query.page) : 1,
				
				// 每页条数
				limit: this.$route.query.limit ? parseInt(this.$route.query.limit) : this.app.limit,
				
				// 总数
				total: this.$route.query.total ? parseInt(this.$route.query.total) : 0,
				
				// 可选择的搜索类型列表
				field: {
					list: [],
					id: this.$route.query.field || "",
				},
				
				// 搜索关键词
				keyword: this.$route.query.keyword || "",
				
				// 时间
				time: this.$route.query.time ? this.$route.query.time.split(",") : [],
				
				// 过滤某些类型
				filter: [],
				
			};
		},
		computed: {
			
			// 过滤类型筛选
			filerComputed(){
				return function(key){
					let filerItem = { select: [], value: [] };
					this.filter.filter((item, index) => {
						(item.field === key) && (filerItem = item);
					});
					return filerItem;
				}
			},
			
			// 统计一下退款笔数
			countRefund(){
				let _this = this;
				return function(e){
					let allList = [];
					let refundList = [];
					if(e.latest_receipt_info){
						allList = allList.concat(e.latest_receipt_info);
					}
					if(e.receipt && e.receipt.in_app){
						allList = allList.concat(e.receipt.in_app);
					}
					
					allList.map((item, index) => {
						if(item.cancellation_date){
							refundList.push({
								cancellation_reason: item.cancellation_reason,
								cancellation_date: item.cancellation_date,
							})
						}
					})
					return refundList;
				}
			},
			
		},
		methods: {
			
			// 加载列表
			getList(){
				let _this = this;
				let filterData = {}; //筛选的参数
				_this.filter.map((item) => filterData[item.field] = item.value.join(","));
				_this.app.ajax({
					url: "/admin/order/index",
					method: "POST",
					data: Object.assign({
						keyword: _this.keyword,
						field: _this.field.id,
						limit: _this.limit,
						page: _this.page,
						time: _this.time ? _this.time.join(",") : "",
					}, filterData),
					load: _this.load,
					changeUrl: true,
					success(res){
						res.data.list.map((item) => {
							item.iapLoad = false;
							item.iapResult = null;
						});
						
						_this.total_channel = res.data.total_channel;
						_this.total = res.data.total;
						_this.tableData = res.data.list;
						_this.field.list = res.data.fields;
						_this.field.id = _this.field.id || res.data.fields[0].value;
						
						res.data.filter.map((item) => {
							item.value = _this.$route.query[item.field] ? _this.$route.query[item.field].split(",") : [];
						});
						_this.filter = res.data.filter;
					}
				})
			},
			
			// 筛选变更
			filterChange(e) {
				this.filter.map((item) => {
					if(item.field === Object.keys(e)[0]){
						item.value = e[item.field];
					}
				});
				
				this.$nextTick(() => {
					this.page = 1;
					this.getList();
				});
			},
			
			// 退款
			refund(index){
				let _this = this
				_this.$prompt(`请输入退款金额（最大${_this.tableData[index].pay_amount}元）`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
				}).then(({ value }) => {
					if(value === undefined || value === "" || value === null){
						_this.$notify({title: '提示',message: '请输入退款金额',type: 'warning'});
						return;
					}
			
					let amount = Number(_this.tableData[index].pay_amount);
					let money = Number(value);
					if(money <= amount){
						_this.app.ajax({
							url: "/admin/order/refund",
							method: "POST",
							data: {
								id: _this.tableData[index].id,
								refund_amount: money,
								refund_reason: "管理员系统后台处理退款",
							},
							load: _this.load,
							success(res){
								_this.$notify({title: '提示',message: res.msg,type: 'success'});
							}
						})
					}else{
						_this.$notify({title: '提示',message: '输入的金额必须小于订单金额',type: 'warning'});
					}
				});
			},
			
			// 查询苹果套餐
			async findStatusIOS(){
				let _this = this;
				for(let i = 0; i < _this.tableData.length; i++){
					if(_this.tableData[i].pay_type !== 'apple'){
						continue;
					}
					await _this.findIapPost(_this.tableData[i]);
				}
			},
			
			// 请求iap订阅post
			findIapPost(item){
				let _this = this;
				return new Promise((resolve) => {
					item.iapLoad = true;
					item.iapResult = null;
					_this.app.ajax({
						url: "/admin/order/getDecodeReceipt",
						data: { order_no: item.order_no },
						method: "POST",
						success(res) {
							item.iapLoad = false;
							item.iapResult = res.data;
							resolve();
						},
						error(err){
							item.iapLoad = false;
							_this.$notify({ title: "提示", message: err.msg, type: "warning" });
							resolve();
						}
					});
				});
			},
			
		},
		mounted(){
			this.getList();
		}
	};
</script>

<style lang="scss" scoped>
	.tableRight{
		flex: 1;
		width: 0;
		text-align: right;
		a{
			font-size: 13px;
			&:hover{
				cursor: pointer;
			}
		}
	}
	.smallLoad{
		flex-direction: row;
		align-items: center;
		.el-icon-loading{
			margin-left: 7px;
		}
	}
	.userLog{
		.item{
			flex-direction: row;
			align-items: center;
			justify-content: space-between;
			font-size: 12px;
			margin-bottom: 15px;
			&:nth-last-child(1){
				margin-bottom: 0;
			}
			.left{
				color: #767676;
			}
			.right{
				color: #333;
				margin-left: 12px;
			}
		}
	}
</style>